import turbogears   as tg

import logging
import cherrypy
from sqlalchemy.exceptions  import SQLError

import kaizen.controllers
from kaizen.model           import Action, Project, Context, session
from turbogears             import identity, expose, validate, validators, redirect, error_handler, flash,view
from formencode             import validators
from textile                import textile
import turbolucene
from turbolucene import *

log = logging.getLogger("kaizen.subcontrollers.project")



class ProjectController:

    @expose(template="kaizen.templates.viewProject", content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def new(self, tg_errors=None, **kw):
        #if no title given
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict(tg_template="kaizen.templates.createProject")
        try:
          title=kw['title']
          notes=kw['notes']
          log.debug("new project. Title = " +title +".")
          project = Project(title=title, notes=notes)
          project.flush()
        #todo add code completion
        except SQLError:
           tg.flash("Project already exists")
           return dict()
        tg.flash("Project added")
        kaizen.controllers.project_provider.update()
        turbolucene.add(project)
        return dict(success=True, project=project)

    @expose(allow_json=True, content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def update(self, id, tg_errors=None, **kw):
        #if no title given
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict()
        project = session.get(Project,int(id))
        title=kw['title']
        notes=kw['notes']
        try:
          log.debug("edit project. Title = " +title +"," +"notes = " +notes)
          project.title=title
          project.notes=notes
          project.flush()
        except SQLError:
           tg.flash("Project already exists")
           return dict()
        tg.flash("Project updated")
        kaizen.controllers.project_provider.update()
        log.debug("returning project. notes = " +project.notes)
        notes = textile(notes.encode('utf-8'), encoding='utf-8', output='ascii')
        turbolucene.update(project)
        return dict(success=True, notes=notes, title=title)

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @error_handler()
    def delete(self, id, tg_errors=None, **kw):
        project = session.get(Project, id)
        project.delete()
        project.flush()
        tg.flash("Project deleted")
        kaizen.controllers.project_provider.update()
        turbolucene.remove(project)
        return dict(success=True)

    @expose(template="kaizen.templates.viewProject", content_type='text/html; charset=utf-8')
    @error_handler()
    def load(self, post_id, **keywords):
        project = session.get(Project, post_id)
        return dict(project=project,previousPage="kaizen.templates.viewProject")

    @expose(template="kaizen.templates.editProject", content_type='text/html; charset=utf-8')
    @error_handler()
    #TODO no use?. It's a simple forward
    def edit(self, id, **keywords):
        log.debug("edit project. id = " +id)
        project = session.get(Project, int(id))
        log.debug("edit project. id = " +str(project.id) +" title=" +project.title +" notes=" +project.notes)
        for action in project.actions:
            log.debug("action = " +str(action))
        return dict(project=project)

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @error_handler()
    def close(self, id, **keywords):
        log.debug("close Project " +id +".")
        project = session.get(Project,id)
        project.closed=1
        project.flush()
        kaizen.controllers.project_provider.update()
        kaizen.controllers.closed_project_provider.update()
        tg.flash("Project closed")
        return dict()

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @error_handler()
    def open(self, id, **keywords):
        log.debug("open Project " +id +".")
        project = session.get(Project,id)
        project.closed=0
        project.flush()
        kaizen.controllers.project_provider.update()
        kaizen.controllers.closed_project_provider.update()
        tg.flash("Project re-opened")
        return dict(project=project)